<?php

namespace app\index\controller;
use think\Validate;
use app\common\model\activity\CouponsCoup as CouponsCoupModel;
use app\common\model\oms\Brands as BrandsModel;
use app\common\model\oms\StoreAuth as StoreAuthModel;
use app\common\model\activity\CouponsBrands as CouponsBrandsModel;
use app\common\model\activity\CouponsStore as CouponsStoreModel;
use app\common\model\activity\SalesActivity as SalesActivityModel;
use app\common\model\activity\Coupons as CouponsModel;
use app\common\model\activity\SalesChannel as SalesChannelModel;
use app\common\model\activity\SalesActivityChannel as SalesActivityChannelModel;
use app\common\model\oms\Store as StoreModel;
use app\index\service\StaffService;
use app\common\model\jooj_member\ViewMemberIndex as ViewMemberIndexModel;
use think\Cache;

class Coupons extends \app\common\controller\AuthBase {

    public function __construct() {
        parent::__construct();
    }

    
    /**
     * 创建/保存卡券
     */
    public function saveCoupons(){
        
        $params = $this->request->param();
        $rule = [
            "id" => 'number',
            "store_name"=>'max:15',
            "store_logo"=>'max:256',
            "color"=>'max:20',
            "date_type"=>'number|between:1,2',
            "start_date"=>'number|max:11',
            "end_date"=>'number|max:11',
            "start_day"=>'number|max:2',
            "end_day"=>'number|max:2',
            "cover_logo"=>'max:256',
            "cover_introduce"=>'max:26',
            "cover_describe"=>'max:600',
            "number"=>'number|max:6',
            'company_id'=>'number|max:11',
            'store_type'=>'number|between:1,4',
            'brands_type'=>'number|between:1,2',
            "get_limit"=>'number|max:6',
            "coupon_name"=>'max:26',
            "coupon_name_sub"=>'max:32',
            "use_instruction"=>'max:600',
            "stores"=>'array',
            "brands"=>'array',
            "entrance"=>'max:4',
            "href"=>'max:256',
            'number_action_type'=>'max:4',
            'change_number'=>'number|max:11',
            'api_user_id'=>'number|max:11',
        ];
        
        if(isset($params['id']) && is_numeric($params['id'])){
            $rule['coupon_name']='max:1000';
            $rule['coupon_name_sub']='max:1000';   
            $rule['cover_introduce']='max:1000';   
            $rule['cover_describe']='max:1000';   
        }
        
        $validate = new Validate($rule);
        if(!$validate->check($params)){
            return $this->output([], $validate->getError());
        }
        
        if(isset($params['id']) && is_numeric($params['id'])){
            //去掉所有的不是必须的参数
            $params = $this->_filterUpdate($params);
        }else{
            $params['add_date'] = time();
            //验证数据之间的关系
            $ret = $this->_validateAdd($params);
            if($ret !== true){
                return $this->output([], $ret);
            }
        }
        
        $res = $this->_validateLegal($params['company_id'], $params);
        if($res !== true){
            return $this->output([], $res);
        }
        
        $couponsModel = new CouponsModel();
        $couponsModel->startTrans();
        $coupons = $couponsModel->saveCoupons($params);
        if($coupons === false){
            return $this->output([], 'failed to save coupons');
        }
        
        $coupons_id = isset($params['id'])?$params['id']:intval($coupons);
        
        $couponsBrandsModel = new CouponsBrandsModel();
        $couponsBrandsModel->startTrans();
        // 添加品牌关联表
        if (isset($params['brands']) && isset($params['brands_type']) && $params['brands_type'] == 2 ) {
            // 添加品牌关联表
            $result2 = $couponsBrandsModel->saveCouponsBrands($coupons_id, $params['brands']);
            if ($result2 <= 0) {
                return $this->output([], 'failed to save coupon brands');
            }
        }
        
        $couponsStoreModel = new CouponsStoreModel();
        $couponsStoreModel->startTrans();
        if (isset($params['stores']) && isset($params['store_type']) && $params['store_type'] == 4 ) {
            // 添加门店关联表
            $result2 = $couponsStoreModel->saveCouponsStore($coupons_id, $params['stores']);
            if ($result2 <= 0) {
                return $this->output([], 'store coupon save failed');
            }
        }
        
        $return = ['coupons_id'=>$coupons_id];
        
        //必须按照顺序commit
        $couponsStoreModel->commit();
        $couponsBrandsModel->commit();
        $couponsModel->commit();
        
        return $this->output($return, 'success');
    }
    
   
    
    
    /**
     * 过滤更新操作的参数
     * @param type $params
     * @return type
     */
    private function _filterUpdate($params){
        
        $filterKeys = [
            "id",
            "color",
            "coupon_name_sub",
            "date_type",
            "start_date",
            "end_date",
            "start_day",
            "end_day",
            "cover_logo",
            "cover_introduce",
            "number",
            "use_instruction",
            "stores",
            "get_limit",
            "number",
            "entrance",
            "href",
            'company_id',
            'store_type',
            "number_action_type",
            "change_number",
            "api_user_id",
        ];
        
        foreach ($params as $key => $value) {
            if (!in_array($key, $filterKeys)) {
                unset($params[$key]);
            }
        }
        return $params;
    }
    
    /**
     * 验证参数
     * @param type $params
     * @return boolean
     */
    private function _validateAdd($params){
         
        $filterKeys = [
            'store_name',
            'store_logo',
            'color',
            'coupon_name',
            'date_type',
            'cover_logo',
            'cover_introduce',
            'cover_describe',
            'get_limit',
            'number',
            'company_id',
            'store_type',
            'brands_type',
            'add_date',
        ];
        
        if ($params['date_type'] == 1) {
            $filterKeys = array_merge($filterKeys, ['start_date', 'end_date']);
        } else {
            $filterKeys = array_merge($filterKeys, ['end_day']);
        }
        
        if ($params['brands_type'] != 1) {
            $filterKeys = array_merge($filterKeys,['brands']);
        }
        
        if (!in_array($params['store_type'], [1, 2, 3])) {
            $filterKeys = array_merge($filterKeys,['stores']);
        }
        
        foreach ($filterKeys as $key) {
            if (!isset($params[$key]) || empty($params[$key])) {
                return "the params {$key} is empty";
            }
        }

        return true;
        
    }
    
    /**
     * 验证参数之间的合法性【门店和品牌】
     * @param type $companyId
     * @param type $params
     */
    private function _validateLegal($companyId,$params){
        
        //如果有选定品牌，判断是不是所有选中的品牌都是合法的
        if (isset($params['brands']) && is_array($params['brands']) && !empty($params['brands'])) {
            $brandsModel = new BrandsModel();
            $brandsList = $brandsModel->getMutli(['company_id'=>$companyId,'is_delete'=>0]);
            
            $brands = array_column($brandsList, 'brand_id');
            $diff_brands = array_diff($params['brands'], $brands);
            
            if(!empty($diff_brands)){
                return "不存在的品牌(".current($diff_brands).")";
            }
        }
        
        //判断是不是所有门店都是合法的
        if (isset($params['stores']) && is_array($params['stores']) && !empty($params['stores'])) {
            $storeAuthModel = new StoreAuthModel();
            $storeAuthList = $storeAuthModel->getMulti(['o_id'=>$companyId]);
            
            $stores = array_column($storeAuthList,'store_id');
            $diff_stores = array_diff($params['stores'], $stores);
            
            if(!empty($diff_stores)){
                return "不存在的门店(".current($diff_stores).")";
            }
        }
        
        return true;
    }
    
    
    /**
     * 获取集团下优惠券列表
     * @param type $company_id
     * @param type $params
     * @return type
     */
    public function getCouponsListByCompanyId() {
        $params = $this->request->param();
        $rule = [
            "company_id" => 'require|number|max:11',
            "params"=>'array'
        ];
        
        $validate = new Validate($rule);
        if(!$validate->check($params)){
            return $this->output([], $validate->getError());
        }
        //验证参数
        if (!$params['company_id']) {
            return $this->output([], 'company_id is null');
        }
        
        $couponsModel = new CouponsModel();
        $data = $couponsModel->Lists($params['company_id'], $params['params']);
        
        return $this->output($data,'success');
    }
    
    /**
     * 领取卡券
     */
    public function receiveCoupons(){
        
        $params = $this->input();
        $rule = [
            "activity_id" => 'require|number|max:11',
            "channel_id" => 'require|number|max:11',
            "mobile"=>'require|mobile',
            "date"=>'require|number|max:11',
            "get_date"=>'require|number|max:11',
            "open_id"=>'max:50',
            "claim_open_id"=>'max:50',
            "claim_date"=>'number|max:11',
            "claim_mpid"=>'number|max:11',
            "is_share"=>'number',
            "vip_id"=>'max:50',
        ];
         
        $validate = new Validate($rule);
        if(!$validate->check($params)){
            return $this->output([], $validate->getError());
        }
        
        $salesActivityModel = new SalesActivityModel();
        //查看销售活动表有没有记录
        $activity = $salesActivityModel->getOne(['id'=>$params['activity_id']]);
        if (empty($activity) || empty($activity['coupons_id'])) {
            return $this->output([], "sales activity record error.");
        }
        
        //核对记录的值
        $now = time();
        if ($now < $activity['start_date']) {
            return $this->output([], "the date of the coupon hasn't arrived yet");
        }

        if ($now > $activity['end_date']) {
            return $this->output([], "the date of the coupon has passed");
        }
        
        if ($activity['status'] != 1) {
             return $this->output([], "the date of the coupon has close");
        }
        
        $couponsModel = new CouponsModel();
        $coupons = $couponsModel->getOne(['id'=>$activity['coupons_id']]);
        
        if (empty($coupons)) {
            return $this->output([], "card coupons do not exist");
        }
        
        $couponsCoupModel = new CouponsCoupModel();
        $totalNum = $couponsCoupModel->getReceiveTotal($params['mobile'], $activity['coupons_id'], $activity['company_id']);
        //超出领取限制
        if ( $totalNum >= $coupons['get_limit']) {
            return $this->output([], "card coupons received beyond the limit");
        }
        
        //验证销售渠道对不对
        $salesChannelModel = new SalesChannelModel();
        $salesChannel = $salesChannelModel->getOne(['id'=>$params['channel_id']]);
        if (empty($salesChannel)) {
             return $this->output([], "sales channel is empty");
        }
        if ($salesChannel['status'] == 0) {
            return $this->output([], "sales channel is close");
        }
        
        
        $saleActivityChannelModel = new SalesActivityChannelModel();
        $activityChannel = $saleActivityChannelModel->getOne([
            'activity_id'   => $params['activity_id'],
            "channel_id"    => $params['channel_id']
        ]);
        
        if (empty($activityChannel)) {
            return $this->output([], "sales activity channel is empty");
        }
        
        if ($activityChannel['status'] == 0) {
            return $this->output([], "sales activity channel is close");
        }
        
        
        $result = $couponsModel->receive($params, [
            "activity" => $activity,
            "channel" => $activityChannel,
            "coupons" => $coupons,
            "activityChannel" => $activityChannel,
        ]);

        if ($result === false) {
            return $this->output([], "coupons is zero");
        } else {
            return $this->output($result, "success");
        }
        
    }
    
    
    
    /**
     * 商城领取卡券
     */
    public function mallReceiveCoupons(){
        
        $params = $this->request->param();
        $rule = [
            "coupons_id"=>'require|number|max:11',
            "mobile"=>'require|mobile',
            "date"=>'require|number|max:11',
            "get_date"=>'require|number|max:11',
            "unique_id"=>'max:50',
            "claim_open_id"=>'max:50',
            "open_id"=>'max:50',
            "claim_date"=>'number|max:11',
            "claim_mpid"=>'number|max:11',
            "is_share"=>'number',
            "vip_id"=>'max:50',
        ];
         
        $validate = new Validate($rule);
        if(!$validate->check($params)){
            return $this->output([], $validate->getError());
        }
        
        $couponsModel = new CouponsModel();
        $coupons = $couponsModel->getOne(['id'=>$params['coupons_id']]);
        
        if (empty($coupons)) {
            return $this->output([], "card coupons do not exist");
        }
        
        $couponsCoupModel = new CouponsCoupModel();
        
        if(!empty($params['unique_id'])){
            //如果已经领过了卡券就直接返回数据
            $couponsCoup = $couponsCoupModel->getCouponsByUniqueId($coupons['id'], $coupons['company_id'],$params['unique_id']);
            if($couponsCoup){
                 return $this->output(['code'=>$couponsCoup['sn']],'success');
            }
        }
        
        $totalNum = $couponsCoupModel->getReceiveTotal($params['mobile'], $params['coupons_id'], $coupons['company_id']);
        //超出领取限制
        if ( $totalNum >= $coupons['get_limit']) {
            return $this->output([], "card coupons received beyond the limit");
        }
        
        $params['activity_id'] = 0;
        $params['channel_id']  = 0;
        $result = $couponsModel->receive($params, [
            "activity" => ['company_id' => $coupons['company_id']],
            "channel" => 0,
            "coupons" => $coupons,
            "activityChannel" => [],
        ]);

        if ($result === false) {
            return $this->output([], "coupons is zero");
        } else {
            return $this->output($result, "success");
        }
        
    }
    
    
    /**
     * 商城批量领取卡券
     */
    public function mallBatchReceiveCoupons(){
        
        $params = $this->request->param();
        $rule = [
            "coupons_id"=>'require|number|max:11',
            "mobile"=>'require|mobile',
            "date"=>'require|number|max:11',
            "get_date"=>'require|number|max:11',
            "unique_id"=>'require|max:50',
            "claim_open_id"=>'max:50',
            "open_id"=>'max:50',
            "claim_date"=>'number|max:11',
            "claim_mpid"=>'number|max:11',
            "is_share"=>'number',
            "vip_id"=>'max:50',
            "coupons_num"=>'require|number',
        ];
         
        $validate = new Validate($rule);
        if(!$validate->check($params)){
            return $this->output([], $validate->getError());
        }
        
        $couponsModel = new CouponsModel();
        $coupons = $couponsModel->getOne(['id'=>$params['coupons_id']]);
        
        if (empty($coupons)) {
            return $this->output([], "card coupons do not exist");
        }
        
        $couponsCoupModel = new CouponsCoupModel();
        
        if(!empty($params['unique_id'])){
            //如果已经领过了卡券就直接返回数据
            $couponsCoup = $couponsCoupModel->getBatchCouponsByUniqueId($coupons['id'], $coupons['company_id'],$params['unique_id']);
            if($couponsCoup){
                foreach($couponsCoup as &$item){
                    $item['code'] = $item['sn'];
                }
                return $this->output($couponsCoup,"success");
            }
        }
        
        $couponsNum = intval($params['counpons_num'])>0?intval($params['coupons_num']):1;
        $totalNum = $couponsCoupModel->getReceiveTotal($params['mobile'], $params['coupons_id'], $coupons['company_id']);
        //超出领取限制
        if ( $totalNum + intval($couponsNum) > $coupons['get_limit']) {
            return $this->output([], "card coupons received beyond the limit");
        }
        
        $params['activity_id'] = 0;
        $params['channel_id']  = 0;
        $result = $couponsModel->batchReceive($params, [
            "activity" => ['company_id' => $coupons['company_id']],
            "channel" => 0,
            "coupons" => $coupons,
            "activityChannel" => [],
        ]);

        if ($result === false) {
            return $this->output([], "coupons is zero");
        } else {
            return $this->output($result, "success");
        }
        
    }
    
    
    
    /**
     * 通过openId获取卡券信息
     * @param type $companyId
     * @param type $openId
     * @param type $status
     * @param type $pageCondition
     * @return type
     */
    public function getCouponsListByOpenId() {
        
        $params = $this->request->param();
        $rule = [
            "company_id" => 'require|number',
            "open_id" => 'require|max:50',
            "status" => 'require|number|between:0,4',
            "page" => 'require|number',
            "pageSize"=>"require|number|between:1,50"
        ];
         
        $validate = new Validate($rule);
        if(!$validate->check($params)){
            return $this->output([], $validate->getError());
        }
        
        $couponsCoupModel = new CouponsCoupModel();
        $couponsModel = new CouponsModel();
        $storeModel = new StoreModel(); 

        $myCouponsList = $couponsCoupModel->getCouponsListByOpenId($params['company_id'], $params['open_id'], $params['status'], $params['page'],$params['pageSize']);
        //如果有继续 否则弹出错误
        if ($myCouponsList) {
            //根据卡券ID找卡券的标题和内容
            foreach ($myCouponsList as $key => $value) {
                $myCouponsList[$key]['info'] = $couponsModel->getCouponsInfoById($value['coupon_id'], $params['companyId']);
                //重置有效期
                $myCouponsList[$key]['info']['start_date'] = $value['start_date'];
                $myCouponsList[$key]['info']['end_date'] = $value['end_date'];
                //组装门店信息
                $myCouponsList[$key]['storeInfo'] = $storeModel->detail($value['store_id'], $params['company_id']);
            }
            return $this->output($myCouponsList, 'success');
        } else {
            return $this->output([], '查询的叽叽券不存在');
        }
    }
    
    /*
     * @Title：SOA根据vip_id获取叽叽券
     * @Time:2017-8-17
     */
    public function getMyCouponsByVipId() {
        
        $params = $this->request->param();
        $rule = [
            "company_id" => 'require|number',
            "vip_id" => 'require',
            'status'=>'require|number|between:0,4',
            'page'=>'number',
            'pageSize'=>'number|between:1,200'
        ];
        
        $validate = new Validate($rule);
        if(!$validate->check($params)){
            return $this->output([], $validate->getError());
        }
        
        //获取我的卡券（ID）
        $couponsCoupModel = new CouponsCoupModel();
        $couponsModel = new CouponsModel();

        $myCoupons = $couponsCoupModel->getMyCouponsByVipId($params['company_id'], 
                $params['vip_id'], $params['status'], $params['page'],$params['pageSize']);

        if(empty($myCoupons)){
            return $this->output([], 'coupons list is empty');
        }
        
        $storeModel = new StoreModel();
        //如果有继续 否则弹出错误
        //根据卡券ID找卡券的标题和内容
        foreach ($myCoupons as $key => $value) {
            //组装券信息
            $myCoupons[$key]['info'] = $couponsModel->getCouponsInfoById($value['coupon_id'], $params['company_id']);
            //重置有效期
            $myCoupons[$key]['info']['start_date'] = $value['start_date'];
            $myCoupons[$key]['info']['end_date'] = $value['end_date'];
            //组装门店信息
            //if()
            $filed = [
                'store_id',
                'company_id',
                'store_show_name',
                'store_address',
                'store_telephone',
            ];
            $myCoupons[$key]['storeInfo'] = $storeModel->detail($value['store_id'], $filed);

            unset($myCoupons[$key]['id']);
        }
        
        return $this->output($myCoupons, 'success');
        
    }
    
    /*
     * @Title：SOA根据叽叽券ID获取叽叽券详情
     * @Time:2017-08-17
     */

    public function getCouponInfoByCouponCoupId() {

        $params = $this->request->param();
        $rule = [
            "company_id" => 'require|number',
            "coupon_coup_id" => 'require|number'
        ];
        
        $validate = new Validate($rule);
        if(!$validate->check($params)){
            return $this->output([], $validate->getError());
        }
        
        //根据ID获取领券信息
        $couponsCoupModel = new CouponsCoupModel();
        $couponsModel = new CouponsModel();
        $couponsBrandsModel = new CouponsBrandsModel();
        
        $couponCoupInfo = $couponsCoupModel->getCouponCoupInfoById($params['coupon_coup_id'], $params['company_id']);
        
        if ($couponCoupInfo && !empty($couponCoupInfo['coupon_id'])) {
            
            $couponInfo = $couponsModel->getCouponsInfoById($couponCoupInfo['coupon_id'], $params['company_id']);
            //根据领券信息中的券IDD获取券的适用品牌
            $couponsBrandsInfo = $couponsBrandsModel->getBrandsByCouponsId($couponCoupInfo['coupon_id']);
            //组装信息
            $couponInfo['start_date'] = $couponCoupInfo['start_date']; //有效期使用领到的券的表的有效期
            $couponInfo['end_date'] = $couponCoupInfo['end_date'];
            //其它参数
            $couponInfo['sn'] = $couponCoupInfo['sn'];
            $couponInfo['status'] = $couponCoupInfo['status'];
            $couponInfo['brands'] = $couponsBrandsInfo;
            
        } else {
            return $this->output([], 'coupons is empty');
        }


        //如果有继续 否则弹出错误
        if ($couponInfo) {
            return $this->output($couponInfo, 'success');
        } else {
            return $this->output([], 'coupons result is empty');
        }
    }
    
    /**
     * 获取集团下优惠券列表，修改活动时使用
     * @param type $company_id
     * @param type $params
     * @return type
     */
    public function getCouponsListForEditActivity() {
        
        $params = $this->request->param();
        $rule = [
            "company_id" => 'require|number',
            "keywords" => 'max:26',
            "page"=>'number',
            "pageSize"=>'number|between:1,200'
        ];
        
        $validate = new Validate($rule);
        if(!$validate->check($params)){
            return $this->output([], $validate->getError());
        }
        
        $couponsModel = new CouponsModel();
        $result = $couponsModel->ListsForEditActivity($params['company_id'], $params['keywords']
                ,$params['page'],$params['pageSize']);
        
        return $this->output($result, 'success');
    }
    
    /**
     * 卡券核销
     * @param type $storeId
     * @param type $staff_id
     * @param type $sn
     * @return type
     */
    public function heXiaoCoupons() {
        //验证参数
        $params = $this->input();
        $rule = [
            "store_id" => 'require|number|max:11',
            "staff_id" => 'require|number|max:11',
            "sn"       => 'require|max:50',
        ];
        
        $validate = new Validate($rule);
        if(!$validate->check($params)){
            return $this->output([], $validate->getError());
        }
        
        $companyId = substr($params['sn'], 0, 4); //取券码前4位，就是 companyId
        $companyId = intval($companyId); //字符串变成数字
        //调用检查核销的方法，检查券
        
        try{
            $result = $this->checkHeXiaoCoupons($params['sn']);
        } catch (\Exception $ex){
            return $this->output([],$ex->getMessage());
        }
        
        $couponCoupInfo = $result['couponCoupInfo'];

        //更新
        $updateData = array(
            'status' => 1,
            'staff_id' => $params['staff_id'],
            'use_date' => time(),
            'store_id' => $params['store_id']
        );
        $couponCoupModel = new CouponsCoupModel();
        $num = $couponCoupModel->updateCouponCoupById($companyId, $couponCoupInfo['id'], $updateData);
        if ($num) {
            //加积分
            $StaffLogic = new StaffService();
            try{
                $StaffLogic->addCompanyStaffPoint($companyId, 1, $params['staff_id'], '核销加积分');
            } catch (\Exception $ex){
                //to do.....
            }
            
            //加入队列，推送给微商城
            $StoreModel = new StoreModel();
            $storeInfo = $StoreModel->getStoreByCondition(['store_id' => $params['store_id']],[
                "store_id","company_code","alliance_id","store_name",
                "store_show_name","store_branch_name","store_longitude","store_latitude",
                "wx_poi_id","wx_sync_status","trusteeship_id","store_type","store_telephone",
                "store_address","store_postcode","store_open_time","store_close_time",
                "special_service","average_consume","region_province_id","region_city_id",
                "region_district_id","store_saletime","ibeacon_status","bu_name"]);

            Cache::select(0);
            Cache::lPush('data_soa_coupon_hexiao', serialize(['coupon_sn' => $couponCoupInfo['sn'],'store_name'=>$storeInfo['store_show_name'],'bu_name'=>$storeInfo['bu_name'],'type' => 'jooj']));

            Cache::select(6);
            Cache::lPush('data_soa_coupon_hexiao', serialize(['coupon_sn' => $couponCoupInfo['sn'], 'couponStatus' => '1', 'store_id' => "{$params['store_id']}", 'use_date' => $updateData['use_date'], 'type' => 'jooj']));
            
            return $this->output($result, 'success');
        }
        
        return $this->output([], "核销失败,{$couponCoupInfo['id']}");
    }
    
    /**
     * 判断验证叽叽券是否正确（对外接口）
     * @return type
     */
    public function checkCoupons(){
        $params = $this->input();
        $rule = [
            "sn"       => 'require|max:50',
        ];
        
        $validate = new Validate($rule);
        if(!$validate->check($params)){
            return $this->output([], $validate->getError());
        }
        
        try{
            $result = $this->checkHeXiaoCoupons($params['sn']);
            return $this->output($result, 'success');
        } catch (\Exception $ex){
            return $this->output([], $ex->getMessage());
        }
    }


    /**
     * 判断一下核销的卡券
     * @param type $sn
     * @return type
     */
    private function checkHeXiaoCoupons($sn) {
        
        //从券码里面获得 companyId
        $companyId = substr($sn, 0, 4); //取券码前4位，就是 companyId
        $companyId = intval($companyId); //字符串变成数字
        
        $couponCoupModel = new CouponsCoupModel();
        $couponCoupInfo = $couponCoupModel->getCouponCoupInfoBySn($companyId, $sn);
        
        if (!$couponCoupInfo) {
            throw new \Exception("此卡券不存在[$companyId]");
        }
        //判断日期
        $now = time();
        if ($couponCoupInfo['start_date'] > $now) {
            throw new \Exception('这张卡券还未到开始使用日期！');
        }

        if ($couponCoupInfo['end_date'] < $now) {
            throw new \Exception("这张卡券已经过期了！");
        }
        if ($couponCoupInfo['status'] == 1){
            throw new \Exception('这张卡券已经使用了！');
        }
        if ($couponCoupInfo['status'] == 4){
            throw new \Exception('这张卡券已经被取消！');
        }
        //验证状态
        if ($couponCoupInfo['status'] != 0) {
            throw new \Exception('此卡券不可使用！');
        }

        // 验证门店
        $conponModel = new CouponsModel();
        $couponInfo  = $conponModel->getCouponsInfoById($couponCoupInfo['coupon_id'], $companyId);
        
        //获得券批次信息
        if (empty($couponInfo)) {
            throw new \Exception("卡券信息错误({$couponCoupInfo['coupon_id']})");
        }
        
        //获得绑定活动信息
        $SalesActivityModel = new SalesActivityModel();
        $activityInfo = $SalesActivityModel->getOne(['coupons_id'=>$couponCoupInfo['coupon_id']]);

        $return = array(
            'couponInfo' => $couponInfo,
            'couponCoupInfo' => $couponCoupInfo,
            'activityInfo' => $activityInfo,
        );
        
        return $return;
    }
    
    
    /*
     * @Title：SOA根据叽叽券ID获取叽叽券详情
     * @param:$couponId(卡券ID);
     * @return:json
     * @Author:李聪颖
     * @Time:2016-4-15
     */
    public function getCouponInfoById() {
        
        $params = $this->input();
        $rule = [
            "coupon_id" => 'require|number|max:11',
            "company_id" => 'require|number|max:11',
        ];
        
        $validate = new Validate($rule);
        if(!$validate->check($params)){
            return $this->output([], $validate->getError());
        }

        //根据ID获取领券信息
        $couponsModel = new CouponsModel();
        $couponInfo = $couponsModel->getCouponsInfoById($params['coupon_id'], $params['company_id']);
        $couponInfo = $this->TransModelArr($couponInfo);
        //组装品牌数据
        $couponsBrandsModel = new CouponsBrandsModel();
        $brandList = $couponsBrandsModel->getBrandsListByCouponsId($params['coupon_id']);
        $couponInfo['brandlist'] = $brandList;
        
        //组装门店数据
        $couponsStoreModel = new CouponsStoreModel();
        $storeList = $couponsStoreModel->getStoreListByCouponsId($params['coupon_id']);
        $couponInfo['storelist'] = $storeList;
        //如果有继续 否则弹出错误
        if ($couponInfo) {
            return $this->output($couponInfo, 'success');
        }
        
        return $this->output([], '卡券的信息不存在！');
    }
    
    
    /*
     * @Title：SOA根据openid更新叽叽券（领到的券）
     * @param:$companyId(集团编号);
     * @param:$openId(会员VIPID);
     * @return:json
     * @Author:李聪颖
     * @Time:2016-4-12
     */
    public function updateMyCouponsByOpenId() {

        $params = $this->request->param();
        $rule = [
            "open_id" => 'require|max:50',
            "company_id" => 'require|number|max:11',
        ];
        
        $validate = new Validate($rule);
        if(!$validate->check($params)){
            return $this->output([], $validate->getError());
        }
        
        $viewMemberIndexModel  = new ViewMemberIndexModel($params['company_id']);
        //获取账号信息
        $viewMemberIndexOpenId = $viewMemberIndexModel->getViewInfoByCondition(['account_code'=>$params['open_id']]);

        $viewMemberIndexOpenId = current($viewMemberIndexOpenId);
        $vipId = $viewMemberIndexOpenId['vip_id'];

        $ret   = false;
        
        if ($vipId > 0) {
            $couponsCoupModel = new CouponsCoupModel();
            $ret = $couponsCoupModel->updateMyCouponsByOpenId($params['company_id'], $params['open_id'], $vipId, $viewMemberIndexOpenId['mobile']);
        }

        if($ret){
            return $this->output([], 'success',"update success $vipId");
        }
        
        return $this->output([], "update fail " . $params['company_id'] . " openid: " . $params['open_id'] . "；vipId: " . $vipId);
    }
    
    
    
    /*
     * @Title：SOA根据叽叽券sn获取叽叽券详情
     * @param:$couponId(卡券ID);
     * @return:json
     * @Author:李聪颖
     * @Time:2016-4-12
     */
    public function getCouponInfoByCouponSn() {
        
        $params = $this->input();
        $rule = [
            "sn" => 'require|max:50',
            "company_id" => 'require|number|max:11',
        ];
        
        $validate = new Validate($rule);
        if(!$validate->check($params)){
            return $this->output([], $validate->getError());
        }
        //根据ID获取领券信息
        $couponsCoupModel = new CouponsCoupModel();
        $couponCoupInfo = $couponsCoupModel->getCouponCoupInfoBySn($params['company_id'],$params['sn']);

        if ($couponCoupInfo) {
            //根据领券信息中的券ID获取券的信息
            if ($couponCoupInfo['coupon_id'] > 0) {
                
                $couponsModel = new CouponsModel();
                $couponInfo   = $couponsModel->getCouponsInfoById($couponCoupInfo['coupon_id'], $params['company_id']);
                //根据领券信息中的券IDD获取券的适用品牌
                $couponsBrandsModel = new CouponsBrandsModel();
                $couponsBrandsInfo = $couponsBrandsModel->getBrandsByCouponsId($couponCoupInfo['coupon_id']);
                //组装信息
                //组装信息
                $couponInfo['start_date'] = $couponCoupInfo['start_date']; //有效期使用领到的券的表的有效期
                $couponInfo['end_date'] = $couponCoupInfo['end_date'];

                $couponInfo['sn'] = $couponCoupInfo['sn'];
                $couponInfo['status'] = $couponCoupInfo['status'];
                $couponInfo['brands'] = $couponsBrandsInfo;
            } else {
                return $this->output([], '卡券信息不存在！');
            }
        } else {
            return $this->output([], '卡券信息不存在：coupon_id:'.$couponCoupInfo['coupon_id'] ." company_id:". $params['company_id']);
        }


        //如果有继续 否则弹出错误
        if ($couponInfo) {
            return $this->output($couponInfo, 'success');
        } else {
            return $this->output([], '卡券信息不存在！');
        }
    }

}
